﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CApPCPreviewComponentApp
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.PreviewComponents;
using EngineeringInternalExtension;
using EngineeringInternalExtension.ModelObjects;
using EngineeringInternalExtension.Options;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.PrivateImplementationDetails;


namespace DnProcessSimulateCommands;

internal class CApPCPreviewComponentApp
{
  private TxSnapshot _snapshot;
  private bool _visibleWorkingFrame;
  private bool _visibleFloor;
  private StringBuilder _logWritter;
  private int _successfullyCreatedPreviews;
  private List<Color> _colors;

  public void CreateComponentPreviewImage(ITxComponent component)
  {
    if (component is TxCable)
      return;
    TxCollisionRoot collisionRoot = TxApplication.ActiveDocument.CollisionRoot;
    bool checkCollisions = collisionRoot.CheckCollisions;
    if (checkCollisions)
      collisionRoot.CheckCollisions = false;
    this.CreateComponentPreviewImageInternal(component);
    if (!checkCollisions)
      return;
    collisionRoot.CheckCollisions = true;
  }

  private void CreateComponentPreviewImageInternal(ITxComponent component)
  {
    TxApplication.ActiveSelection.Clear();
    this.BeforeTakeImage();
    Image previewImage = !TxFeatureManager.CheckFeature("QUALITY_COMPONENT_PREVIEW") ? (Image) TxGraphicViewerEx1.GetObjectImage(TxApplication.ViewersManager.GraphicViewer, (ITxObject) component, new Size(200, 153)) : (Image) TxGraphicViewerEx1.GetObjectImage(TxApplication.ViewersManager.GraphicViewer, (ITxObject) component, new Size(500, 500));
    if (previewImage != null)
      this.SaveComponentPreviewImage(component, previewImage);
    this.AfterTakeImage();
  }

  public bool CreateComponentsPreviewImage(string componentsFolder)
  {
    List<string> componentsFolders = this.ExtractComponentsFolders(componentsFolder);
    this.CreateLog();
    this.CreateComponentsPreviewImage(componentsFolders);
    this.ShowLog(string.Format(ComponentPreviewResource.PREVIEW_CREATED_COMPONENTS_MESSAGE, (object) this._successfullyCreatedPreviews, (object) (componentsFolders.Count - this._successfullyCreatedPreviews)));
    return componentsFolders.Count > 0;
  }

  public void CreateComponentsPreviewImage(List<string> componentPaths)
  {
    this.BlankStudy();
    this.SetViewPoint();
    if (TxFeatureManager.CheckFeature("QUALITY_COMPONENT_PREVIEW"))
      this.SetViewStyles();
    this._successfullyCreatedPreviews = 0;
    foreach (string componentPath in componentPaths)
    {
      ITxComponent component = this.InsertComponent(componentPath);
      if (component != null)
      {
        ++this._successfullyCreatedPreviews;
        this.ComponentPreview(component);
        this.DeleteComponent(component);
      }
    }
    if (TxFeatureManager.CheckFeature("QUALITY_COMPONENT_PREVIEW"))
      this.RestoreViewStyles();
    this.RestoreStudy();
  }

  private List<string> ExtractComponentsFolders(string componentsFolder)
  {
    List<string> componentsFolders = new List<string>();
    if (!componentsFolder.EndsWith(".cojt"))
    {
      foreach (DirectoryInfo directory in new DirectoryInfo(componentsFolder).GetDirectories("*.cojt", SearchOption.AllDirectories))
        componentsFolders.Add(directory.FullName);
    }
    else
      componentsFolders.Add(componentsFolder);
    return componentsFolders;
  }

  private void BlankStudy()
  {
    this.TakeSnapshot();
    TxDisplayableObjectEx.Blank((ITxDisplayableObject) TxApplication.ActiveDocument.PhysicalRoot, false);
    this.BeforeTakeImage();
  }

  private void BeforeTakeImage()
  {
    this._visibleWorkingFrame = TxOptionsEx.ShowWorkingFrame;
    TxOptionsEx.ShowWorkingFrame = false;
    TxApplication.ViewersManager.GraphicViewer.DisplayOrientationFrameOfReference(false);
    this._visibleFloor = TxApplication.ViewersManager.GraphicViewer.Floor.Visibility;
    TxApplication.ViewersManager.GraphicViewers.ForEach((Action<TxGraphicViewer>) (x => x.Floor.Visibility = false));
  }

  private void SetViewPoint()
  {
    TxApplication.ViewersManager.GraphicViewer.SetCameraOrientation(Math.PI / 6.0, Math.PI / 6.0);
  }

  private void SetViewStyles()
  {
    this._colors = TxApplication.ViewersManager.GraphicViewer.BackgroundColors;
    TxApplication.ViewersManager.GraphicViewer.BackgroundColors = new List<Color>()
    {
      Color.Transparent,
      Color.Transparent,
      Color.Transparent,
      Color.Transparent
    };
  }

  private void RestoreViewStyles()
  {
    TxApplication.ViewersManager.GraphicViewer.BackgroundColors = this._colors;
  }

  private void DisplayComponent(ITxDisplayableObject component)
  {
    if (component == null)
      return;
    TxDisplayableObjectEx.Display(component, false);
    this.BlankAllFrames();
  }

  private void BlankAllFrames()
  {
    TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxFrame)));
    for (int index = 0; index < ((Collection<ITxObject>) allDescendants).Count; ++index)
      TxDisplayableObjectEx.Blank(((Collection<ITxObject>) allDescendants)[index] as ITxDisplayableObject, false);
  }

  private void SendCableVisibilityObservers()
  {
    TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxCable)));
    for (int index = 0; index < ((Collection<ITxObject>) allDescendants).Count; ++index)
    {
      ITxDisplayableObject displayableObject = ((Collection<ITxObject>) allDescendants)[index] as ITxDisplayableObject;
      if (displayableObject.Visibility == null)
      {
        TxDisplayableObjectEx.Blank(displayableObject, true);
        TxDisplayableObjectEx.Display(displayableObject, true);
      }
    }
  }

  private ITxComponent InsertComponent(string componentPath)
  {
    ITxComponent itxComponent = (ITxComponent) null;
    try
    {
      itxComponent = TxApplication.ActiveDocument.PhysicalRoot.InsertComponent(new TxInsertComponentCreationData(TxApplication.ActiveDocument.PhysicalRoot.GetUniqueDisplayName("component"), componentPath));
      this.LogSucceesMessage(componentPath);
    }
    catch (Exception ex)
    {
      this.LogFailedMessage(componentPath);
    }
    return itxComponent;
  }

  private void DeleteComponent(ITxComponent component) => ((ITxObject) component).Delete();

  private void ComponentPreview(ITxComponent component)
  {
    TxApplication.ViewersManager.GraphicViewer.ZoomToFit();
    Image previewImage = !TxFeatureManager.CheckFeature("QUALITY_COMPONENT_PREVIEW") ? (Image) TxGraphicViewerEx1.GetObjectImage(TxApplication.ViewersManager.GraphicViewer, (ITxObject) component, new Size(200, 153)) : (Image) TxGraphicViewerEx1.GetObjectImage(TxApplication.ViewersManager.GraphicViewer, (ITxObject) component, new Size(500, 500));
    if (previewImage == null)
      return;
    this.SaveComponentPreviewImage(component, previewImage);
  }

  private void SaveComponentPreviewImage(ITxComponent component, Image previewImage)
  {
    string str = TxComponentEx.Get3DDataFullPath(component as ITxStorable);
    previewImage.Save(str + "\\preview.bmp", ImageFormat.Bmp);
  }

  private void RestoreStudy()
  {
    this.AfterTakeImage();
    this.ApplySnapshot();
    this.DeleteSnapshot();
    this.SendCableVisibilityObservers();
  }

  private void AfterTakeImage()
  {
    TxApplication.ViewersManager.GraphicViewers.ForEach((Action<TxGraphicViewer>) (x => x.Floor.Visibility = this._visibleFloor));
    TxOptionsEx.ShowWorkingFrame = this._visibleWorkingFrame;
    TxGraphicViewerEx.The.ResetOrientationFrameOfReference();
  }

  private void TakeSnapshot()
  {
    this._snapshot = TxApplication.ActiveDocument.PhysicalRoot.CreateSnapshot(new TxSnapshotCreationData()
    {
      Name = "ComponentPreviewImageCreation"
    });
  }

  private void ApplySnapshot()
  {
    if (!TxSnapshot.op_Inequality(this._snapshot, (ITxObject) null))
      return;
    TxApplySnapshotParams applySnapshotParams = new TxApplySnapshotParams();
    applySnapshotParams.ObjectsLocation = true;
    applySnapshotParams.ObjectsVisibility = true;
    applySnapshotParams.PointOfView = true;
    applySnapshotParams.DevicePoses = true;
    applySnapshotParams.ObjectsAttachments = true;
    applySnapshotParams.ObjectsColor = true;
    applySnapshotParams.ObjectsViewingMode = true;
    applySnapshotParams.PMIsScale = true;
    TxSnapshotEx.SendVisibilityNotification(applySnapshotParams, false);
    this._snapshot.Apply(applySnapshotParams);
  }

  private void DeleteSnapshot()
  {
    if (!TxSnapshot.op_Inequality(this._snapshot, (ITxObject) null))
      return;
    this._snapshot.Delete();
  }

  private void CreateLog() => this._logWritter = new StringBuilder();

  private void LogSucceesMessage(string componentPath)
  {
    this.LogMessage(string.Format(ComponentPreviewResource.SUCCEED_TO_PREVIEW_COMPONENT, (object) componentPath));
    this.LogMessage(Environment.NewLine);
  }

  private void LogFailedMessage(string componentPath)
  {
    this.LogMessage(string.Format(ComponentPreviewResource.FAILED_TO_PREVIEW_COMPONENT, (object) componentPath));
    this.LogMessage(Environment.NewLine);
  }

  private void LogMessage(string message)
  {
    if (this._logWritter == null)
      return;
    this._logWritter.Append(message);
  }

  private void ShowLog(string message)
  {
    if (this._logWritter == null)
      return;
    string str = Path.GetTempPath() + $"CreateCompPreview_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.log";
    StreamWriter streamWriter = new StreamWriter((Stream) new FileStream(str, FileMode.Create));
    streamWriter.Write(this._logWritter.ToString());
    streamWriter.Flush();
    streamWriter.Close();
    if (TxMessageBox.Show(message, ComponentPreviewResource.CREATE_COMP_PREVIEW_CMD_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
      Process.Start(str);
    else
      new FileInfo(str).Delete();
  }
}
